package com.fowo.api.controller.purchase;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.fowo.api.common.model.IdListPo;
import com.fowo.api.common.model.R;
import com.fowo.api.controller.purchase.dto.*;
import com.fowo.api.controller.purchase.vo.PurchasePlansProductVo;
import com.fowo.api.controller.purchase.vo.WarehouseBinParam;
import com.fowo.api.entity.*;
import com.fowo.api.mapper.WarehouseBinDMapper;
import com.fowo.api.model.purchase.order.PurchaseOrderVo;
import com.fowo.api.model.purchase.order.product.PurchaseOrderProductItemVo;
import com.fowo.api.model.purchase.plans.PurchasePlansVo;
import com.fowo.api.model.purchase.plans.product.PurchasePlansProductItemVo;
import com.fowo.api.model.purchase.plans.product.PurchasePlansProductSearchParamPo;
import com.fowo.api.model.receipt.ReceiptVo;
import com.fowo.api.model.stock.in.StockInVo;
import com.fowo.api.model.stock.in.product.StockInProductItemVo;
import com.fowo.api.service.impl.*;
import com.fowo.api.user.model.JwtUserInfo;
import com.fowo.api.util.LocalDateUtils;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Slf4j
@Tag(name = "采购计划接口")
@RequestMapping("/api/customized-purchase-plans")
@RestController
public class PurchasePlansDController {
    @Resource
    private PurchasePlansServiceImpl purchasePlansService;
    @Resource
    private PurchasePlansProductServiceImpl purchasePlansProductService;
    @Resource
    private InventoryRealServiceImpl inventoryRealService;
    @Resource
    private SalesOutboundServiceImpl salesOutboundService;
    @Resource
    private PurchaseOrderServiceImpl purchaseOrderService;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private ProductBaseServiceImpl productService;
    @Resource
    private StockInServiceImpl stockInService;
    @Resource
    private com.fowo.api.service.handleWork.stockInSyncWarehousing stockInSyncWarehousing;
    @Resource
    protected StockInProductServiceImpl stockInProductService;
    @Resource
    protected PurchaseOrderProductServiceImpl purchaseOrderProductService;
    @Resource
    private StockOutServiceImpl stockOutService;
    @Resource
    private PurchaseChangeOrderServiceImpl purchaseChangeOrderService;

    @Resource
    private WarehouseBinServiceImpl warehouseBinService;
    @Resource
    private WarehouseBinDMapper warehouseBinDMapper;
    @Resource
    private WarehouseServiceImpl warehouseService;
    @Resource
    private ReceiptServiceImpl receiptService;


    @Operation(summary = "作废")
    @PostMapping("cancellations")
    public R cancellations(@RequestBody IdListPo po) {
        for (int i = 0; i < po.getIds().size(); i++) {
            Long aLong = po.getIds().get(i);
            try {
                cancellations2(aLong);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    void cancellations2(Long id) throws Exception {
        PurchasePlansVo voById = purchasePlansService.getVoById(id);
        List<PurchasePlansProduct> list = purchasePlansProductService.list(Wrappers.<PurchasePlansProduct>query().lambda().eq(PurchasePlansProduct::getParentPurchasePlans, voById.getId()));
        long count = list.stream().filter(x -> x.getQuantityPurchased() != null && x.getQuantityPurchased() > 0).count();
        Assert.isTrue(count == 0, "已经采购不能作废！");
        voById.setStatus("5");
        purchasePlansService.updateById(voById);
    }

    @Operation(summary = "下单")
    @PostMapping("placeAnOrder2")
    public R placeAnOrder(@RequestBody IdListPo po) {
        for (int i = 0; i < po.getIds().size(); i++) {
            Long aLong = po.getIds().get(i);
            try {
                placeAnOrder2(aLong);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return R.ok(true);
    }

    public void placeAnOrder2(Long id) throws Exception {
        JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
        PurchaseOrderVo voById = purchaseOrderService.getVoById(id);
        Assert.isTrue(voById.getAnStatus().equals("1"), "违规操作！");
        voById.setAnStatus("2");
        voById.setOrderUser(jwtUserInfo.getUserId());
        voById.setOrderTime(new Date());
        purchaseOrderService.updateById(voById);
    }


    @Operation(summary = "获取采购计划生成")
    @PostMapping("DetailedInfo")
    public R detailedInfo(@RequestBody PurchasePlansProductDTO purchasePlansProductDTO) {
        Assert.isTrue(purchasePlansProductDTO.getPlans() != null && purchasePlansProductDTO.getPlans().length > 0, "参数不能为null!");
        List<PurchasePlansProduct> purchasePlans = purchasePlansProductService.list(Wrappers.<PurchasePlansProduct>query().lambda()
                .in(PurchasePlansProduct::getPlanSn, Arrays.asList(purchasePlansProductDTO.getPlans())));
        List<PurchasePlansProductVo> purchasePlansProductVoList = new ArrayList<>();
        for (int i = 0; i < purchasePlans.size(); i++) {
            PurchasePlansProduct purchasePlansProduct = purchasePlans.get(i);
            Long productId = purchasePlansProduct.getProduct();
            Assert.notNull(productId, purchasePlansProduct.getSku() + "在产品表中没有找到信息");
            Product byId = productService.getById(productId);
            PurchasePlansProductVo purchasePlansProductVo = new PurchasePlansProductVo();
            BeanUtils.copyProperties(purchasePlansProduct, purchasePlansProductVo);
            purchasePlansProductVo.setModel(byId.getModel());
            InventoryReal totalInventory = getTotalInventory(productId);
            purchasePlansProductVo.setTotalInventory(totalInventory != null ? totalInventory.getStockQty() : 0);
            purchasePlansProductVoList.add(purchasePlansProductVo);
        }
        return R.data(purchasePlansProductVoList);
    }

    //分页获取采购计划所有产品
    @Operation(summary = "查询")
    @GetMapping
    public R<List<PurchasePlansProductItemVo>> search(
            PurchasePlansProductSearchParamPo search
    ) {
        //获取所有待采购状态的采购计划 等待采购
        search.setStatus("2");
        //筛选等待采购数量大于0的
//        search.setNoQuantityPurchasedGt(0);
        return R.data(purchasePlansProductService.search(search));
    }

    @Operation(summary = "获取合并的数据")
    @PostMapping("purchaseOrderMerge")
    public R purchaseOrderMerge(@RequestBody PurchasePlansDTO model) {
        Map<String, List<PurchasePlansProduct>> map2 = model.getPurchasePlansProducts().stream().collect(Collectors.groupingBy(d -> fetchGroupKey(d)));
        Set<String> PlanSn = map2.keySet();
        JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
        List<PurchaseOrderVo> list = new ArrayList<>();
        List<Long> oversightUid = new ArrayList<>();
        for (String key : PlanSn) {
            List<PurchasePlansProduct> purchasePlansProductDTO2s = map2.get(key);
            //数据进行拆分
            String[] s = key.split("_");
            PurchaseOrderVo purchaseOrderVo = new PurchaseOrderVo();
            purchaseOrderVo.setId(Convert.toLong(s[0]));
            purchaseOrderVo.setRemarks(model.getOrderRemarkSear());
            purchaseOrderVo.setSupplierId(Convert.toLong(s[1]));
            purchaseOrderVo.setWid(Convert.toLong(s[0]));
            purchaseOrderVo.setIncludingTax(model.getIncludingTax());
            purchaseOrderVo.setFeePartType(model.getFeePartType());
            oversightUid.add(jwtUserInfo.getUserId());
            purchaseOrderVo.setOversightUid(oversightUid);
            purchaseOrderVo.setShippingPrice(model.getShippingPrice());
            purchaseOrderVo.setOtherCurrency(model.getOtherCurrency());
            purchaseOrderVo.setOptUid(jwtUserInfo.getUserId());
            purchaseOrderVo.setInspectionType(model.getInspectionType());
            List<PurchaseOrderProductItemVo> purchaseOrde = new ArrayList<>();
            for (int i = 0; i < purchasePlansProductDTO2s.size(); i++) {
                PurchasePlansProduct purchasePlansProduct = purchasePlansProductDTO2s.get(i);
                PurchaseOrderProductItemVo purchaseOrderProductItemVo = new PurchaseOrderProductItemVo();
                purchaseOrderProductItemVo.setApplicationNum(purchasePlansProduct.getPsqMod());
                purchaseOrderProductItemVo.setQuantityReceive(purchasePlansProduct.getPsqMod());
                purchaseOrderProductItemVo.setProductId(purchasePlansProduct.getProduct());
                purchaseOrderProductItemVo.setSku(purchasePlansProduct.getSku());
                purchaseOrderProductItemVo.setPicUrl(purchasePlansProduct.getPicUrl());
                purchaseOrderProductItemVo.setFnsku(purchasePlansProduct.getFnsku());
                purchaseOrderProductItemVo.setMsku(purchasePlansProduct.getMsku());
                purchaseOrderProductItemVo.setExpectArriveTime(purchasePlansProduct.getExpectArriveTime());
                purchaseOrderProductItemVo.setPlanSn(purchasePlansProduct.getPlanSn());
//                purchaseOrderProductItemVo.setRemarks(purchasePlansProduct.getRemarks());
                purchaseOrderProductItemVo.setSid(purchasePlansProduct.getSid());
//                purchaseOrderProductItemVo.setFnsku(purchasePlansProduct.getFnsku());
                purchaseOrderProductItemVo.setMsku(purchasePlansProduct.getMsku());
                purchaseOrde.add(purchaseOrderProductItemVo);
            }
            purchaseOrderVo.setPurchaseOrde(purchaseOrde);
            list.add(purchaseOrderVo);
        }
        return R.data(list);
    }

    private static String fetchGroupKey(PurchasePlansProduct model) {
        //按照仓库+供应商进行分组
        return model.getWid() + "_" + model.getSupplierId();
    }

    @Operation(summary = "新增")
    @PostMapping
    public synchronized R create(@RequestBody List<PurchaseOrderVo> model) {

//        String execute = transactionTemplate.execute(new TransactionCallback<String>() {
//            @Override
//            public String doInTransaction(TransactionStatus status) {
//                try {
//                    for(int i=0;i<model.size();i++){
//                        PurchaseOrderVo purchaseOrderVo = model.get(i);
//                        purchaseOrderVo.setAStatus("0");
//                        purchaseOrderVo.setArrivalStatus("0");
//                        purchaseOrderService.create(purchaseOrderVo);
//                        //修改采购计划的采购量
//                        updatePurchasePlansProductStatus(purchaseOrderVo);
//                    }
//                } catch (Exception e) {
//                    log.error(model.toString(),e.getLocalizedMessage(),e.toString());
//                    Assert.isTrue(true,e.getLocalizedMessage());
//                }
//                return "1";
//            }
//        });
        AtomicReference<String> str = new AtomicReference<>();
        Boolean execute1 = transactionTemplate.execute(status -> {
            try {
                for (int i = 0; i < model.size(); i++) {
                    PurchaseOrderVo purchaseOrderVo = model.get(i);
                    purchaseOrderVo.setId(null);
                    purchaseOrderVo.setAnStatus("0");
                    purchaseOrderVo.setProductType("1");//默认产品类型是成品
                    purchaseOrderVo.setArrivalStatus("0");
                    purchaseOrderService.create(purchaseOrderVo);
                    //修改采购计划的采购量
                    updatePurchasePlansProductStatus(purchaseOrderVo);
                }
            } catch (Exception e) {
                log.error(model.toString(), e.getLocalizedMessage(), e.toString());
                str.set(e.getLocalizedMessage());
                status.setRollbackOnly();
                return Boolean.FALSE;
            }
            return Boolean.TRUE;
        });

        if (execute1) {
            return R.success("新增完成!", 0);
        } else {
            return R.fail("新增失败!" + str.toString());
        }
    }

    //更新采购订单子表的状态,如果数量大于就改成已完成
    private synchronized void updatePurchasePlansProductStatus(@RequestBody PurchaseOrderVo model) {
        List<PurchaseOrderProductItemVo> list = model.getPurchaseOrde().stream().filter(x -> x.getPlanSn() != null).collect(Collectors.toList());
        //筛选出所有采购计划下来的采购单子，按照采购计划分组
        Map<String, Integer> collect = list.stream().collect(Collectors.groupingBy(PurchaseOrderProductItemVo::getPlanSn, Collectors.summingInt(PurchaseOrderProductItemVo::getApplicationNum)));
        Set<String> PlanSn = collect.keySet();
        for (String key : PlanSn) {
            Integer total = collect.get(key);
            PurchasePlansProduct purchasePlansProduct = purchasePlansProductService.getOne(Wrappers.<PurchasePlansProduct>query().lambda().eq(PurchasePlansProduct::getPlanSn, key));
            Assert.notNull(purchasePlansProduct, key + "不存在！");
            Assert.isTrue(purchasePlansProduct.getStatus().equals("2"), purchasePlansProduct.getPlanSn() + "已完成状态或者未审核状态不能生成采购订单！");
            //获取之前已经采购的数量
            Integer count = purchasePlansProduct.getQuantityPurchased() == null ? 0 : purchasePlansProduct.getQuantityPurchased();
            if (count + total >= purchasePlansProduct.getQuantityPlan()) {
                purchasePlansProduct.setStatus("3");
            }
            Integer quantityPurchased = purchasePlansProduct.getQuantityPurchased() + total;
            //修改发货的数量
            purchasePlansProduct.setQuantityPurchased(quantityPurchased);
            //修改未发货的数量
            purchasePlansProduct.setNoQuantityPurchased(purchasePlansProduct.getQuantityPlan() - quantityPurchased < 0 ? 0 : purchasePlansProduct.getQuantityPlan() - quantityPurchased);
            purchasePlansProductService.updateById(purchasePlansProduct);
            //修改主表已发货数量
            PurchasePlans purchasePlans = purchasePlansService.getById(purchasePlansProduct.getParentPurchasePlans());
            Long quantityPurchased1 = purchasePlans.getQuantityPurchased() != null ? purchasePlans.getQuantityPurchased() : 0;
            purchasePlans.setQuantityPurchased(quantityPurchased1 + total);
            purchasePlansService.updateById(purchasePlans);
        }
        //修改主表的完成状态
        updateMainPurchasePlansStats(PlanSn);
    }

    //修改状态
    private void updateMainPurchasePlansStats(Set<String> planSn) {
        List<PurchasePlansProduct> list = purchasePlansProductService.list(Wrappers.<PurchasePlansProduct>query().lambda().in(PurchasePlansProduct::getPlanSn, planSn));
        //获取涉及到的主表id
        Set<Long> collect = list.stream().map(PurchasePlansProduct::getParentPurchasePlans).collect(Collectors.toSet());
        List<PurchasePlans> list1 = purchasePlansService.list(Wrappers.<PurchasePlans>query().lambda().in(PurchasePlans::getId, collect));
        for (int i = 0; i < list1.size(); i++) {
            PurchasePlans purchasePlans = list1.get(i);
            if (purchasePlans.getQuantityPurchased() >= new BigDecimal(purchasePlans.getQuantityPlan()).longValue()) {
                //修改为已完成
                purchasePlans.setStatus("3");
                purchasePlansService.updateById(purchasePlans);
            }
        }
    }

    @Operation(summary = "获取店铺的销量信息")
    @PostMapping("getSynchronismSales")
    public R getAmazonOrderQty(@RequestBody WarehouseBinParam warehouseBinParam) {
        Assert.notNull(warehouseBinParam.getStartDate(), "开始时间不能为null");
        Assert.notNull(warehouseBinParam.getEndDate(), "结束时间不能为null");
        AmazonOrderListProductDetail amazonOrderQty = warehouseBinDMapper.getAmazonOrderQty(warehouseBinParam);
        return R.data(amazonOrderQty);
    }

    @Operation(summary = "获取店铺的库存信息")
    @PostMapping("getShopSales")
    public R getShopSales(@RequestBody PurchasePlansProductDTO purchasePlansProductDTO) {
        //获取店铺的信息 purchaseProductDTOs
        Assert.notNull(purchasePlansProductDTO.getPurchaseProductDTOs(), "purchaseProductDTOs参数没传");
        for (int i = 0; i < purchasePlansProductDTO.getPurchaseProductDTOs().size(); i++) {
            PurchaseProductDTO purchaseProductDTO = purchasePlansProductDTO.getPurchaseProductDTOs().get(i);
            //获取本店库库存
            InventoryReal shopInventory = getShopInventory(purchaseProductDTO, 1);
            //获取其他店铺库存
            InventoryReal shopInventory1 = getShopInventory(purchaseProductDTO, 2);
            //获取公共的库存
            InventoryReal shopInventory2 = getShopInventory(purchaseProductDTO, 3);
            purchaseProductDTO.setLocalShopInventory(shopInventory != null ? shopInventory.getStockQty() : 0);
            purchaseProductDTO.setOtherShopInventory(shopInventory1 != null ? shopInventory1.getStockQty() : 0);
            purchaseProductDTO.setPublicInventory(shopInventory2 != null ? shopInventory2.getStockQty() : 0);
        }
        return R.data(purchasePlansProductDTO.getPurchaseProductDTOs());
    }

    //获取所有仓库的库存
    private InventoryReal getTotalInventory(long productId) {
        QueryWrapper<InventoryReal> queryWrapper = new QueryWrapper();
        queryWrapper.select("sum(stock_qty) as  stock_qty");
        queryWrapper.eq("item_id", productId);
        return inventoryRealService.getOne(queryWrapper);
    }

    //获取店铺的库存,如果没有店铺查询公共仓库的库存
    private InventoryReal getShopInventory(PurchaseProductDTO purchaseProductDTO, Integer type) {

        QueryWrapper<InventoryReal> queryWrapper = new QueryWrapper();
        queryWrapper.select("sum(stock_qty) as  stock_qty");
        queryWrapper.eq("item_id", purchaseProductDTO.getProductId());
        queryWrapper.eq("stock_id", purchaseProductDTO.getWid());
        //查询本店铺的
        if (type == 1) {
            if (purchaseProductDTO.getSid() != null) {
                Assert.isTrue(purchaseProductDTO.getSid() != null && purchaseProductDTO.getFnsku() != null, "请选择FNSKU");
            }
            queryWrapper.eq(purchaseProductDTO.getSid() != null, "shop_id", purchaseProductDTO.getSid());
            queryWrapper.eq(purchaseProductDTO.getFnsku() != null, "fn_sku", purchaseProductDTO.getFnsku());
        }
        //查询其他的店铺的
        else if (type == 2) {
            if (purchaseProductDTO.getSid() == null) {
                return null;
            }
            queryWrapper.ne(purchaseProductDTO.getSid() != null, "shop_id", purchaseProductDTO.getSid());
        }
        //查询公共的库存
        else if (type == 3) {
            queryWrapper.isNull("shop_id");
            queryWrapper.isNull("fn_sku");
        }
        return inventoryRealService.getOne(queryWrapper);
    }

    //获取销量
    private SalesOutbound getSales(Date startDate, Date endDate, String sku, Long sid) {
        QueryWrapper<SalesOutbound> queryWrapper = new QueryWrapper();
        queryWrapper.select("sum(quantity) as  quantity");
        queryWrapper.eq("sid", sid);
        queryWrapper.eq("account_type", "Standard");
        queryWrapper.eq("event_type", "Shipment");
        queryWrapper.eq("local_sku", sku);
        queryWrapper.eq("type", "Principal");
        queryWrapper.between("posted_date_locale", LocalDateUtils.format(startDate, LocalDateUtils.DATE_PATTERN) + " 00:00:00", LocalDateUtils.format(endDate, LocalDateUtils.DATE_PATTERN) + " 23:59:59");
        queryWrapper.groupBy("local_sku");
        SalesOutbound one = salesOutboundService.getOne(queryWrapper);
        return one;
    }

    //下推入库单后置处理
    public void stock_in(JSONObject args) throws Exception {

        Assert.notNull(args, "参数不能为null");
//        purchaseArgsDTO purchaseArgs = JSON.parseObject(args.toJSONString(), purchaseArgsDTO.class);
        purchaseArgsDTO purchaseArgs = JSONUtil.toBean(args.toJSONString(), purchaseArgsDTO.class);
        PurchaseOrder one = purchaseOrderService.getOne(Wrappers.<PurchaseOrder>query().lambda().eq(PurchaseOrder::getPurchaseOrderCode, purchaseArgs.getFromMap().getPurchaseOrderCode()));

        PurchaseChangeOrder purchaseChangeOrder = purchaseChangeOrderService.getOne(Wrappers.lambdaQuery(PurchaseChangeOrder.class)
                .eq(PurchaseChangeOrder::getOrderSn, one.getPurchaseOrderCode())
                .eq(PurchaseChangeOrder::getStatus, "0"));
        Assert.isNull(purchaseChangeOrder, "采购订单:" + one.getPurchaseOrderCode() + "变更单待审批");

        //新增入库单和入库单子表
        StockInVo stock = new StockInVo();
        stock.setWarehouse(Long.valueOf(purchaseArgs.getFromMap().getWid()));//设置仓库
        stock.setSupplier(Long.valueOf(purchaseArgs.getFromMap().getSupplierId()));//设置供应商
        stock.setReceiptType("RK002");
//        stock.setAStatus("pending");//productType
        stock.setAStatus("completed");
        stock.setStatus("1");
        stock.setAddType("1");
        stock.setRemarks(one.getRemarks());
        stock.setFreight(purchaseArgs.getToMap().getFreight());//运费
        stock.setOtherExpenses(purchaseArgs.getToMap().getOtherExpenses());//其他费用
        //stock.setWarehousingDate(purchaseArgs.getToMap().getReceiptDate()!=null?LocalDateUtils.toDate(purchaseArgs.getToMap().getReceiptDate(),LocalDateUtils.DATE_PATTERN):new  Date());//入库时间
        String receiptDate = purchaseArgs.getToMap().getReceiptDate();
        if (StrUtil.isEmpty(receiptDate)) {
            stock.setWarehousingDate(new Date());//入库时间
        } else {
            Long receiptDateL = Convert.toLong(receiptDate, null);
            stock.setWarehousingDate(receiptDateL != null ? DateUtil.date(receiptDateL) : Convert.toDate(receiptDate, new Date()));//入库时间
        }
        stock.setProductType("1");//成品
        stock.setCostAllocationType(one.getFeePartType());
        stock.setCgUid(one.getOptUid());
        stock.setGenerateAp("0");

        stock.setPurchasingOrg(one.getPurchasesOrg());
        stock.setNeedOrg(one.getSettlementOrg());
        stock.setWarehousingDate(new Date());
        //stock.setTotalNum();//总数量
        stock.setCgUid(one.getOptUid());//associatedPo
        stock.setAssociatedPo(purchaseArgs.getToMap().getOrderSn());//收货单号
        stock.setPurchaseOrderCode(purchaseArgs.getFromMap().getPurchaseOrderCode());//采购单号
        List<StockInProductItemVo> productList = new ArrayList<>();
        //查询库位
        WarehouseBin warehouseBin = warehouseBinService.getOne(Wrappers.<WarehouseBin>query().lambda()
                .eq(WarehouseBin::getWarehouseId, stock.getWarehouse())
                .eq(WarehouseBin::getStorageBin, "待检暂存"));

        for (int i = 0; i < purchaseArgs.getChildren().size(); i++) {
            purchaseArgsDTO.ChildrenDTO childrenDTO = purchaseArgs.getChildren().get(i);
            PurchaseOrderProduct purchaseOrderProduct = purchaseOrderProductService.getById(childrenDTO.getFromMap().getId());
            //修改可退货数量
            purchaseOrderProduct.setCrossChecking(purchaseOrderProduct.getCrossChecking() != null ? purchaseOrderProduct.getCrossChecking() + childrenDTO.getToMap().getReceiptNum() : childrenDTO.getToMap().getReceiptNum());
            if (purchaseOrderProduct.getQuantityReceive() != null) {
                if (purchaseOrderProduct.getQuantityReceive().intValue() < 0) {
                    purchaseOrderProduct.setQuantityReceive(0);
                }
                if (purchaseOrderProduct.getQuantityReceived().intValue() > purchaseOrderProduct.getApplicationNum().intValue()) {
                    purchaseOrderProduct.setApplicationNum(purchaseOrderProduct.getQuantityReceived());
                }
            }
            StockInProductItemVo stockInProductItemVo = new StockInProductItemVo();
            stockInProductItemVo.setUnitPrice(purchaseOrderProduct.getUnitPrice());
            stockInProductItemVo.setProductId(purchaseOrderProduct.getProductId());
            stockInProductItemVo.setPurchaseOrderProductId(childrenDTO.getFromMap().getId());
            stockInProductItemVo.setShopId(purchaseOrderProduct.getSid());
            stockInProductItemVo.setSku(childrenDTO.getFromMap().getSku());
            stockInProductItemVo.setFnsku(purchaseOrderProduct.getFnsku());
            stockInProductItemVo.setImg(purchaseOrderProduct.getPicUrl());
            stockInProductItemVo.setPositions(warehouseBin.getId());
            stockInProductItemVo.setUnitPrice(purchaseOrderProduct.getUnitPrice());
            stockInProductItemVo.setCostPrice(purchaseOrderProduct.getCostPrice());
            stockInProductItemVo.setMainUnitPrice(purchaseOrderProduct.getMainUnitPrice());
            stockInProductItemVo.setGramWeight(purchaseOrderProduct.getGramWeight());
            stockInProductItemVo.setLaborCosts(purchaseOrderProduct.getLaborCosts());
            stockInProductItemVo.setReceiptProductId(childrenDTO.getToMap().getId());
            //辅料价格
            stockInProductItemVo.setAccessoriesPrice(purchaseOrderProduct.getAccessoriesPrice());
            //设置辅料小计价格
            if (purchaseOrderProduct.getAccessoriesPrice() != null) {
                stockInProductItemVo.setAccessoriesPriceAmount(purchaseOrderProduct.getAccessoriesPrice().multiply(new BigDecimal(childrenDTO.getToMap().getReceiptNum() != null ? childrenDTO.getToMap().getReceiptNum().intValue() : 0)));
            }
            stockInProductItemVo.setSubtotal(purchaseOrderProduct.getTotalPrice());
            stockInProductItemVo.setLxFnsku(purchaseOrderProduct.getLxFnsku());
            stockInProductItemVo.setFnskuFnsku(purchaseOrderProduct.getLxFnsku());
            stockInProductItemVo.setLxPrice(purchaseOrderProduct.getLxPrice());
            stockInProductItemVo.setLxTotalPrice(purchaseOrderProduct.getLxTotalPrice());
//            stockInProductItemVo.setFnskuFnsku(purchaseOrderProduct.getFnskuFnsku());
            stockInProductItemVo.setUnitStock(childrenDTO.getToMap().getReceiptNum() != null ? childrenDTO.getToMap().getReceiptNum().intValue() : 0);//到货数量
            stockInProductItemVo.setQuantity(0);//可用数量
            stockInProductItemVo.setWaitQuantity(childrenDTO.getToMap().getReceiptNum() != null ? childrenDTO.getToMap().getReceiptNum().intValue() : 0);
//            stockInProductItemVo.setCostPrice(purchaseOrderProduct.getUnitPrice());
//            stockInProductItemVo.setSubtotal(purchaseOrderProduct.getUnitPrice()!=null?purchaseOrderProduct.getUnitPrice().multiply(new BigDecimal(childrenDTO.getToMap().getReceiptNum())):new BigDecimal("0"));
            productList.add(stockInProductItemVo);
            purchaseOrderProductService.updateById(purchaseOrderProduct);
        }
        Long sum2 = productList.stream().mapToLong(StockInProductItemVo::getWaitQuantity).sum();
        stock.setTotalNum(sum2.toString());
        //回写到货数量totalNum totalNum
        List<purchaseArgsDTO.ChildrenDTO> children = purchaseArgs.getChildren();
        if (one.getQuantityReceived() == null) {
            //到货数量
            long sum1 = children.stream().mapToLong(x -> x.getToMap().getReceiptNum()).sum();
            one.setQuantityReceived(sum1);
        } else {
            long sum1 = children.stream().mapToLong(x -> x.getToMap().getReceiptNum()).sum();
            one.setQuantityReceived(one.getQuantityReceived() + sum1);
        }
        List<PurchaseOrderProduct> list = purchaseOrderProductService.list(Wrappers.<PurchaseOrderProduct>query().lambda().eq(PurchaseOrderProduct::getPurchaseOrderId, one.getId()));
        int sum = list.stream().mapToInt(x -> x.getApplicationNum()).sum();
        one.setPurchaseQuantity(sum + "");
        purchaseOrderService.updateById(one);
//        Double sum = productList.stream().mapToDouble(StockInProductItemVo::getQuantity).sum();
//        stock.setTotalStorage(sum.intValue());
        stock.setProductList(productList);
        Long aLong = stockInService.create(stock);
        //判断采购订单是否完成
        PurchaseOrder one2 = purchaseOrderService.getOne(Wrappers.<PurchaseOrder>query().lambda().eq(PurchaseOrder::getPurchaseOrderCode, purchaseArgs.getFromMap().getPurchaseOrderCode()));
        BigDecimal bigDecimal = new BigDecimal(one2.getPurchaseQuantity());
        if (new BigDecimal(one2.getQuantityReceived()).compareTo(bigDecimal) == 0 || new BigDecimal(one2.getQuantityReceived()).compareTo(bigDecimal) == 1) {
            one2.setArrivalStatus("2");
            one2.setAnStatus("9");
        } else {
            one2.setArrivalStatus("1");
        }
        purchaseOrderService.updateById(one2);
        //审核入库单
        stockInService.ruku3(aLong);
//        stockInSevice.applyInStorage(aLong);
//        stockInService.applyInStorage(aLong);
        //修改收货单日期
        ReceiptVo voById = receiptService.getVoById(purchaseArgs.getToMap().getId());
        if (voById.getReceiptDate() == null) {
            voById.setReceiptDate(new Date());
            receiptService.update(voById);
        }
    }

    @Operation(summary = "下单")
    @PostMapping("placeOrder111")
    public R placeOrder111() throws Exception {
        List<Warehouse> list = warehouseService.list(Wrappers.<Warehouse>query().lambda().eq(Warehouse::getWidType, 1));
        for (int i = 0; i < list.size(); i++) {
            warehouseService.AddWarehouse(list.get(i).getId());
        }
        return null;
    }

    //退货单后置处理,生成出库单
    public void stock_out(JSONObject args) throws Exception {
        Assert.notNull(args, "参数不能为null");
        System.out.print("下推的参数" + args.toString());
//        purchaseReturnArgsDTO purchaseReturnArgs= JSON.parseObject(args.toJSONString(), purchaseReturnArgsDTO.class);
        //把退货数量改回来
        purchaseReturnArgsDTO purchaseReturnArgs = JSONUtil.toBean(args.toJSONString(), purchaseReturnArgsDTO.class);
        for (int i = 0; i < purchaseReturnArgs.getChildren().size(); i++) {
            purchaseReturnArgsDTO.ChildrenDTO childrenDTO = purchaseReturnArgs.getChildren().get(i);
            PurchaseOrderProduct purchaseOrderProduct = purchaseOrderProductService.getById(childrenDTO.getFromMap().getId());
            purchaseOrderProduct.setQuantityReturn(purchaseOrderProduct.getQuantityReturn() - childrenDTO.getToMap().getQuantity().intValue());
            purchaseOrderProduct.setCrossChecking(purchaseOrderProduct.getCrossChecking() + childrenDTO.getToMap().getQuantity().intValue());
            purchaseOrderProductService.updateById(purchaseOrderProduct);
        }

//        purchaseReturnArgsDTO purchaseReturnArgs= JSONUtil.toBean(args.toJSONString(),purchaseReturnArgsDTO.class);
//        StockOutVo model=new StockOutVo();
//        model.setWarehouse(Long.valueOf(purchaseReturnArgs.getToMap().getWid()));
//        model.setProductType("1");//先默认成品的
//        model.setType("CK004");
//        model.setAStatus("40");
//        model.setStatus("0");
//        model.setOutTime(new Date());
//        model.setRemark(purchaseReturnArgs.getToMap().getRemark());
//        List<StockOutProductItemVo> stockOutProducts =new ArrayList<>();
//        for(int i=0;i<purchaseReturnArgs.getChildren().size();i++){
//            purchaseReturnArgsDTO.ChildrenDTO childrenDTO = purchaseReturnArgs.getChildren().get(i);
//            PurchaseOrderProduct purchaseOrderProduct = purchaseOrderProductService.getById(childrenDTO.getFromMap().getId());
//            StockOutProductItemVo stockOutProductItemVo=new StockOutProductItemVo();
//            stockOutProductItemVo.setProductId(Long.valueOf(childrenDTO.getToMap().getProductId()));
//            stockOutProductItemVo.setSku(childrenDTO.getToMap().getProductSku());
//            stockOutProductItemVo.setProductGoodNum(childrenDTO.getToMap().getQuantity().intValue());
//            stockOutProductItemVo.setSid(purchaseOrderProduct.getSid());
//            stockOutProductItemVo.setFnsku(String.valueOf(purchaseOrderProduct.getFnsku()));
//            stockOutProductItemVo.setPrice(purchaseOrderProduct.getUnitPrice());
//            BigDecimal unitPrice=purchaseOrderProduct.getUnitPrice()==null?new BigDecimal("0"):purchaseOrderProduct.getUnitPrice();
//            Long GoodNum=childrenDTO.getToMap().getQuantity()==null?0:childrenDTO.getToMap().getQuantity();
//            stockOutProductItemVo.setQuantity(GoodNum.intValue());
//            stockOutProductItemVo.setSubtotal(new BigDecimal(stockOutProductItemVo.getQuantity()).multiply(unitPrice));
//            stockOutProducts.add(stockOutProductItemVo);
//        }
//        model.setRId(purchaseReturnArgs.getToMap().getId());//设置退货单的id
//        model.setStockOutProducts(stockOutProducts);
//        Long aLong = stockOutService.create(model);
//        //更新采购单退款数量
//        //审核出库单
//        //退货扣款
//        if(purchaseReturnArgs.getToMap().getReturnMethod().equals("1")){
//        //  待定
//        }
//        //退货补货
//        else if(purchaseReturnArgs.getToMap().getReturnMethod()!=null&&purchaseReturnArgs.getToMap().getReturnMethod().equals("2")){
//        //退货补货
//             PurchaseOrder one = purchaseOrderService.getOne(Wrappers.<PurchaseOrder>query().lambda().eq(PurchaseOrder::getPurchaseOrderCode, purchaseReturnArgs.getToMap().getPurchaseOrderCode()));
//
//            for(int i=0;i<purchaseReturnArgs.getChildren().size();i++){
//                purchaseReturnArgsDTO.ChildrenDTO childrenDTO = purchaseReturnArgs.getChildren().get(i);
//                PurchaseOrderProduct purchaseOrderProduct = purchaseOrderProductService.getById(childrenDTO.getFromMap().getId());
//                purchaseOrderProduct.setQuantityReceive(purchaseOrderProduct.getQuantityReceive()+childrenDTO.getToMap().getQuantity().intValue());
//                purchaseOrderProductService.updateById(purchaseOrderProduct);
//            }
//            one.setAStatus("2");
//            one.setArrivalStatus("1");
//            purchaseOrderService.updateById(one);
//        }


    }


}
